import qs from 'qs'
import axios from 'axios'

export const http = axios.create({
  timeout: 20000,
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  withCredentials: true,
  transformRequest: [data => qs.stringify(data)],  // for POST, PUT, PATCH requests
  paramsSerializer: qs.stringify                   // for GET request
})

export function resource(path, http, actions) {
  let defaultActions = {
    get: id => http.get(path + "/" + id),
    del: id => http.delete(path + "/" + id),
    deleteBatch: idArray => http.delete(path, {
      params: {
        items: idArray
      }
    }),
    add: obj => jsonRequest(path, "post", obj),
    modify: obj => jsonRequest(path, "put", obj),
    save: (obj, method) => {
      if (method != "post" && method != 'put') {
        throw new Error('保存只能够为post或get');
      }
      return jsonRequest(path, method, obj)
    },
    list: params => http.get(path + "/list", {params}),
    exists: (rule, value) => {
      let params = {}
      params[rule.field] = value
      return http.get(path + "/validation", {params})
    },
    paging: (vue, page, rows, sortColumn) => pageRequest(vue, page, rows, sortColumn, path),
    http
  }

  return Object.assign(defaultActions, actions)
}

export const jsonRequest = function (path, method, data) {
  return http[method](path, data, {
    headers: {'Content-Type': 'application/json'},
    transformRequest: [data => JSON.stringify(data)]
  })
}

export const pageRequest = (vue, page, rows, sortColumn, path) => {
  vue.laoding = true
  if (rows) {
    vue.table.pageSize = rows
  }
  if (page) {
    vue.table.pageNumber = page
  }
  if (sortColumn) {
    vue.queryParams.sortColumn = sortColumn
  }
  vue.queryParams = Object.assign({}, vue.queryParams, {
    page: vue.table.pageNumber,
    rows: vue.table.pageSize,
  })
  return new Promise((resolve, reject) => {
    http.get(path, {params: vue.queryParams}).then(res => {
      vue.table.rows = res.data.rows
      vue.table.total = res.data.total
      vue.table.pageSize = res.data.pageSize
      vue.table.pageNumber = res.data.pageNumber
      resolve(res)
      vue.$nextTick(() => {
        vue.loading = false
      })
    }).catch(reject)
  })
}

export const User = resource('/user', http, {
  login: (params) => http.post('/login', params),
  register: (obj) => jsonRequest('/register', 'post', obj),
  logout: () => http.get('/logout'),
  registerCheckExists: (rule, value) => {
    let params = {}
    params[rule.field] = value
    return http.post("/exists", params)
  },
  avatar: (obj) => jsonRequest('/user/avatar', 'put', obj),
})

export const Department = resource('/department', http, {
  tree: params => http.get('/department/tree', {params}),
})

export const Permission = resource('/permission', http, {
  tree: params => http.get('/permission/tree', {params}),
  getDefaultPermissionGroup: () => http.get('/permission/defaultPermissionGroup'),
  listMenus: () => http.get("/permission/listMenus"),
  listMenuTree: () => http.get("/permission/listMenuTree"),
  save: (obj, method) => {
    if (method === "post") {
      return jsonRequest("/permission/group", "post", obj)
    } else if (method === "put") {
      return jsonRequest("/permission", "put", obj)
    } else {
      throw new Error('保存只能够为post或get');
    }
  },
})

export const Role = resource('/role', http, {
  rolePermission: roleName => http.get("/permission/rolePermission/" + roleName),
  updateRolePermissions: obj => jsonRequest('/permission/updateRolePermissions', "post", obj),
  userRole: username => http.get("/role/userRoles/" + username),
  saveUserRole: (username, roleIds) => jsonRequest('/role/userRoles', "post", {
    "username": username,
    "roleIds": roleIds
  }),
  setCurrentRole: roleName => http.get("/role/role/current/" + roleName),
  getCurrentRole: () => http.get("/role/role/current"),
})

export const Auth = resource('', http, {
  authorizationCheck: () => http.get("/authorization-check"),
})

export const Dict = resource('/dict', http, {
  delByCode: (code) => http.delete('/dict/cond', {"params": {"code": code}}),
  listByCode: (code) => http.get(`/dict/list/${code}`),
  updateWithAttribute: (obj) => jsonRequest('/dict/updateWithAttribute', 'post', obj),
})

export const FileMapping = resource('/filemapping', http, {
  tree: params => http.get('/filemapping/tree', {params}),
  parents: (id) => http.get('filemapping/parents?parent=' + id), // 获取所有父文件夹
  uploadToken: () => http.get('filemapping/upload/token'),
})
